package com.zzyl.service.impl;


import com.google.common.collect.Lists;
import com.zzyl.constant.Constants;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.service.MemberService;
import com.zzyl.service.WeChatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * @Description MemberServiceImpl
 * @Author liangDong
 * @Date 2025-05-15  16:06
 */
@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private WeChatService weChatService;

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    static List<String> DEFAULT_NICKNAME_PREFIX = Lists.newArrayList(
            "生活更美好",
            "大桔大利",
            "“日富一日",
            "好柿开花",
            "柿柿如意",
            "—椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        //获取openid
        String openId = weChatService.getOpenId(userLoginRequestDto.getCode());
        //根据openid查询用户
        Member member = memberMapper.getByOpenId(openId);
        //用户为空就新增
        if (ObjectUtil.isEmpty(member)){
            member = Member.builder().openId(openId).build();
        }

        //利用phonecode获取手机号
        String phone = weChatService.getPhone(userLoginRequestDto.getPhoneCode());
        //保存或修改用户
        saveOrUpdate(member,phone);
        //将用户id存入token
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(Constants.JWT_USERID,member.getId());
        claims.put(Constants.JWT_USERNAME,member.getName());

        String token = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(),jwtTokenManagerProperties.getTtl(),claims);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(member.getName());
        return loginVo;
    }

    private void saveOrUpdate(Member member,String phone){
    //    判断手机号和数据库的是否一致，不一致就更新
        if (ObjectUtil.notEqual(phone,member.getPhone())){
            member.setPhone(phone);
        }

    //    判断id是否存在，存在就更新
        if (ObjectUtil.isNotEmpty(member.getId())){
            memberMapper.update(member);
            return;
        }
    //    不存在时就新增
        String name = DEFAULT_NICKNAME_PREFIX.get((int)(Math.random()*DEFAULT_NICKNAME_PREFIX.size()))
                + StringUtils.substring(member.getPhone(),7);
        member.setName(name);
        memberMapper.save(member);

    }
}
